<template>
  <div class="page-content">
    <!-- 顶部导航 -->
    <header class="bg-white shadow-sm sticky top-0 z-10">
      <div class="container mx-auto px-4 py-3 flex items-center">
        <router-link to="/" class="mr-2">
          <i class="fas fa-arrow-left text-gray-600"></i>
        </router-link>
        <h1 class="text-lg font-semibold">诉状生成</h1>
      </div>
      <div class="container mx-auto px-4 flex border-b">
        <button
          @click="currentStep = 'case'"
          class="py-3 px-4 font-medium"
          :class="currentStep === 'case' ? 'tab-active' : 'text-gray-500'"
        >
          选择案由
        </button>
        <button
          @click="currentStep = 'input'"
          class="py-3 px-4 font-medium"
          :class="currentStep === 'input' ? 'tab-active' : 'text-gray-500'"
        >
          信息输入
        </button>
        <button
          @click="currentStep = 'save'"
          class="py-3 px-4 font-medium"
          :class="
            currentStep === 'save' ? 'tab-active' : 'text-gray-500 opacity-50'
          "
        >
          保存分享
        </button>
      </div>
    </header>

    <!-- 选择案由步骤 -->
    <main v-if="currentStep === 'case'" class="container mx-auto px-4 mt-4">
      <div class="bg-white rounded-xl shadow-md p-4">
        <h3 class="font-medium mb-2">全部案由</h3>
        <div class="relative input-highlight mb-4">
          <i class="fas fa-search absolute left-3 top-3 text-gray-400"></i>
          <input
            v-model="searchKeyword"
            type="text"
            placeholder="搜索案由..."
            class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none"
          />
        </div>

        <!-- 搜索结果（有关键词时显示） -->
        <div v-if="searchKeyword" class="max-h-60 overflow-y-auto space-y-2">
          <div
            v-for="item in filteredSearchCases"
            :key="item.category + '-' + item.name"
            @click="selectCase(item.name)"
            class="p-2 rounded hover:bg-gray-100 cursor-pointer flex items-center justify-between"
          >
            <span>
              {{ item.name }}
              <span class="ml-2 text-xs text-gray-400">（{{ item.category }}）</span>
            </span>
            <i v-if="item.hot" class="fas fa-fire text-orange-500 text-xs"></i>
          </div>
        </div>

        <!-- 二级树（无关键词时显示） -->
        <div v-else class="max-h-80 overflow-y-auto divide-y">
          <div v-for="cat in categoryList" :key="cat" class="py-2">
            <!-- 类别头 -->
            <div
              class="flex items-center justify-between px-2 py-1 rounded cursor-pointer hover:bg-gray-50"
              @click="expandedCategories[cat] = !expandedCategories[cat]"
            >
              <div class="font-medium text-gray-800">{{ cat }}</div>
              <i :class="['fas', expandedCategories[cat] ? 'fa-chevron-up' : 'fa-chevron-down', 'text-gray-400']"></i>
            </div>

            <!-- 子项列表 -->
            <div v-show="expandedCategories[cat]" class="mt-1 space-y-1">
              <div
                v-for="(name, idx) in caseMap[cat]"
                :key="cat + '-' + name"
                @click="selectCase(name)"
                class="mx-2 px-2 py-1 rounded hover:bg-gray-100 cursor-pointer flex items-center justify-between"
              >
                <span>{{ name }}</span>
                <i v-if="idx < 11" class="fas fa-fire text-orange-500 text-xs"></i>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 信息输入步骤 -->
    <main v-if="currentStep === 'input'" class="container mx-auto px-4 mt-4">
      <div class="bg-white rounded-xl shadow-md p-6 pt-12 relative">
        <div class="absolute top-2 right-4 bg-red-100 text-red-600 px-3 py-1 rounded-full text-sm font-medium">
          离婚纠纷
        </div>
        <div class="space-y-6">
          <!-- 当事人信息 -->
          <div class="input-group relative">
            <div class="flex items-center gap-2 mb-1">
              <label class="text-sm font-medium text-gray-700">当事人信息</label>
              <span class="text-red-500 text-sm">*</span>
              <button type="button" class="p-1 text-gray-400 hover:text-gray-600" @click="openPlaceholderModal('partyInfo', '当事人信息')">
                <i class="fas fa-file-alt"></i>
              </button>
            </div>
            <textarea 
              v-model="formData.partyInfo" 
              maxlength="500"
              rows="3"
              class="w-full px-3 py-2 pl-6 pr-12 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 resize-none"
              :placeholder="placeholders.partyInfo"
            ></textarea>
            <span class="absolute bottom-2 right-2 text-xs text-gray-400">{{ formData.partyInfo.length }}/500</span>
          </div>
          
          <!-- 代理人信息 -->
          <div class="input-group relative">
            <div class="flex items-center gap-2 mb-1">
              <label class="text-sm font-medium text-gray-700">代理人信息</label>
              <button type="button" class="p-1 text-gray-400 hover:text-gray-600" @click="openPlaceholderModal('agentInfo', '代理人信息')">
                <i class="fas fa-file-alt"></i>
              </button>
            </div>
            <textarea 
              v-model="formData.agentInfo" 
              maxlength="200"
              rows="3"
              class="w-full px-3 py-2 pl-6 pr-12 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 resize-none"
              :placeholder="placeholders.agentInfo"
            ></textarea>
            <span class="absolute bottom-2 right-2 text-xs text-gray-400">{{ formData.agentInfo.length }}/200</span>
          </div>
          
          <!-- 诉讼请求 -->
          <div class="input-group relative">
            <div class="flex items-center gap-2 mb-1">
              <label class="text-sm font-medium text-gray-700">诉讼请求</label>
              <span class="text-red-500 text-sm">*</span>
              <button type="button" class="p-1 text-gray-400 hover:text-gray-600" @click="openPlaceholderModal('legalRequests', '诉讼请求')">
                <i class="fas fa-file-alt"></i>
              </button>
            </div>
            <textarea 
              v-model="formData.legalRequests" 
              maxlength="1000"
              rows="4"
              class="w-full px-3 py-2 pl-6 pr-12 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 resize-none"
              :placeholder="placeholders.legalRequests"
            ></textarea>
            <span class="absolute bottom-2 right-2 text-xs text-gray-400">{{ formData.legalRequests.length }}/1000</span>
          </div>
          
          <!-- 事实与理由 -->
          <div class="input-group relative">
            <div class="flex items-center gap-2 mb-1">
              <label class="text-sm font-medium text-gray-700">事实与理由</label>
              <span class="text-red-500 text-sm">*</span>
              <button type="button" class="p-1 text-gray-400 hover:text-gray-600" @click="openPlaceholderModal('factsAndReasons', '事实与理由')">
                <i class="fas fa-file-alt"></i>
              </button>
            </div>
            <textarea 
              v-model="formData.factsAndReasons" 
              maxlength="2000"
              rows="6"
              class="w-full px-3 py-2 pl-6 pr-12 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 resize-none"
              :placeholder="placeholders.factsAndReasons"
            ></textarea>
            <span class="absolute bottom-2 right-2 text-xs text-gray-400">{{ formData.factsAndReasons.length }}/2000</span>
          </div>
        </div>
      </div>
      
      <button
        @click="currentStep = 'save'"
        class="w-full mt-6 bg-gradient-to-r from-blue-600 to-blue-500 hover:from-blue-700 hover:to-blue-600 text-white py-3 px-4 rounded-lg font-medium flex items-center justify-center"
      >
        <i class="fas fa-magic mr-2"></i>
        <span>AI识别生成</span>
      </button>
    </main>

    <!-- 保存分享步骤 -->
    <main v-if="currentStep === 'save'" class="container mx-auto px-4 mt-4">
      <div class="bg-white rounded-xl shadow-md p-6 mb-6">
        <div class="flex items-center mb-4">
          <div
            class="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center mr-3"
          >
            <i class="fas fa-file-word text-blue-600 text-xl"></i>
          </div>
          <div>
            <h3 class="font-medium">借贷纠纷诉状.docx</h3>
            <p class="text-sm text-gray-500">2023-06-15 14:30</p>
          </div>
        </div>

        <div class="flex justify-between">
          <div class="text-sm">
            <p class="text-gray-500">文件大小</p>
            <p class="font-medium">356 KB</p>
          </div>
          <div class="text-sm">
            <p class="text-gray-500">生成时间</p>
            <p class="font-medium">2.3 秒</p>
          </div>
        </div>
      </div>

      <div class="grid grid-cols-2 gap-4">
        <button
          @click="downloadFile"
          class="bg-blue-600 hover:bg-blue-700 text-white py-3 px-4 rounded-lg font-medium flex items-center justify-center"
        >
          <i class="fas fa-eye mr-2"></i>
          <span>查看</span>
        </button>
        <button
          @click="shareFile"
          class="bg-green-600 hover:bg-green-700 text-white py-3 px-4 rounded-lg font-medium flex items-center justify-center"
        >
          <i class="fas fa-share-alt mr-2"></i>
          <span>分享</span>
        </button>
      </div>

      <!-- 补充说明与历史入口 -->
      <div class="mt-5 bg-gray-50 rounded-lg p-3">
        <div class="flex items-start text-gray-600 text-sm">
          <i class="fas fa-info-circle mt-0.5 mr-2"></i>
          <p>文档已自动保存，您可以随时在历史文件中查看与再次分享。</p>
        </div>
        <div class="mt-3 flex justify-center">
          <router-link
            to="/usage-history"
            class="inline-flex items-center text-blue-600 hover:text-blue-700 text-sm font-medium"
          >
            <i class="fas fa-history mr-2"></i>
            <span>查看历史文件</span>
          </router-link>
        </div>
      </div>
    </main>
  </div>
  
  <!-- 占位提示弹窗 -->
  <div
    v-if="placeholderModal.visible"
    class="fixed inset-0 z-50 bg-black bg-opacity-50 flex items-center justify-center"
    @click="closePlaceholderModal"
  >
    <div class="bg-white rounded-lg w-11/12 max-w-md p-4" @click.stop>
      <div class="flex items-center justify-between mb-2">
        <h3 class="text-base font-medium">{{ placeholderModal.title }}</h3>
        <button @click="closePlaceholderModal" class="p-1 text-gray-400 hover:text-gray-600">
          <i class="fas fa-times"></i>
        </button>
      </div>
      <div class="text-sm text-gray-600 whitespace-pre-wrap">{{ placeholderModal.content }}</div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed } from "vue";

export default {
  name: "Generate",
  setup() {
    const currentStep = ref("case");
    const searchKeyword = ref("");

    const formData = reactive({
      plaintiff: "",
      defendant: "",
      amount: "",
      loanDate: "",
      dueDate: "",
      purpose: "",
      hasContract: true,
      partyInfo: "",
      agentInfo: "",
      legalRequests: "",
      factsAndReasons: "",
    });

    // 一级分类与二级案由
    const primaryCategories = reactive(["民商事", "执行", "普通行政", "刑事行政"]);
    const selectedPrimary = ref(primaryCategories[0]);
    const expandedCategories = reactive({
      民商事: true,
      执行: false,
      普通行政: false,
      刑事行政: false,
    });

    const caseMap = reactive({
      民商事: [
        "买卖合同纠纷",
        "租赁合同纠纷",
        "物业服务合同纠纷",
        "继承纠纷",
        "侵权责任纠纷",
        "婚姻家庭纠纷",
        "劳动争议纠纷",
        "建设工程纠纷",
        "知识产权纠纷",
        "公司纠纷",
        "证券纠纷",
        "期货纠纷",
        "保险纠纷",
        "票据纠纷",
        "信用证纠纷",
        "融资租赁纠纷",
        "保理纠纷",
        "典当纠纷",
        "民间借贷纠纷",
        "金融借款纠纷",
        "担保纠纷",
        "保证合同纠纷",
        "抵押合同纠纷",
        "质押合同纠纷",
        "定金合同纠纷",
        "居间合同纠纷",
        "委托合同纠纷",
        "行纪合同纠纷",
        "运输合同纠纷",
        "仓储合同纠纷",
        "技术合同纠纷",
        "特许经营合同纠纷",
        "合伙协议纠纷",
        "股权转让纠纷",
        "公司决议纠纷",
      ],
      执行: [
        "执行申请",
        "执行异议",
        "案外人执行异议",
        "执行异议之诉",
        "不予执行仲裁裁决申请",
        "恢复执行申请",
        "执行复议",
        "保全与执行措施异议",
        "中止执行申请",
        "终结执行申请",
        "变更追加当事人申请",
      ],
      普通行政: [
        "行政处罚",
        "行政强制",
        "行政许可",
        "政府信息公开",
        "行政确认",
        "履行法定职责",
        "行政赔偿",
        "行政复议",
        "征收征用",
        "行政不作为",
      ],
      刑事行政: [
        "取保候审申请",
        "变更强制措施申请",
        "解除强制措施申请",
        "国家赔偿申请",
        "会见申请",
        "阅卷申请",
        "申请调取证据",
        "申请重新鉴定",
        "申请回避",
      ],
    });

    const secondaryCases = computed(() => caseMap[selectedPrimary.value] || []);
    const filteredSecondaryCases = computed(() => {
      if (!searchKeyword.value) return secondaryCases.value;
      return secondaryCases.value.filter((caseType) =>
        caseType.toLowerCase().includes(searchKeyword.value.toLowerCase())
      );
    });

    // 扁平搜索结果（显示类别）
    const categoryList = computed(() => Object.keys(caseMap));
    const flattenedCases = computed(() => {
      return categoryList.value.flatMap((cat) =>
        (caseMap[cat] || []).map((name, idx) => ({ category: cat, name, hot: idx < 11 }))
      );
    });
    const filteredSearchCases = computed(() => {
      if (!searchKeyword.value) return [];
      const kw = searchKeyword.value.toLowerCase();
      return flattenedCases.value.filter((item) => item.name.toLowerCase().includes(kw));
    });

    const legalRequests = reactive([
      {
        title: "判令被告偿还借款本金人民币100,000元",
        basis: "根据《中华人民共和国民法典》第六百七十五条",
        checked: true,
      },
      {
        title: "判令被告支付利息（按LPR四倍计算）",
        basis:
          "根据《最高人民法院关于审理民间借贷案件适用法律若干问题的规定》第二十五条",
        checked: true,
      },
      {
        title: "判令被告承担本案诉讼费用",
        basis: "根据《诉讼费用交纳办法》第二十九条",
        checked: false,
      },
    ]);

    const factsAndReasons = ref(
      "原告与被告系朋友关系。2022年5月10日，被告以生意资金周转为由向原告借款人民币100,000元，约定借款期限为6个月，月利率1.5%，并出具借条一张。借款到期后，经原告多次催讨，被告以各种理由推诿拒不偿还..."
    );

    // 输入框占位文案（用于弹窗与placeholder共享）
    const placeholders = reactive({
      partyInfo: "当事人信息 (如: 原告:张三,男,身份证号:3301XXXXXXXXXXXX,住址:杭州市西湖区...)",
      agentInfo: "代理人信息 (如: 李四,浙江XX律师事务所律师,联系电话:138xxxxxx)",
      legalRequests: "诉讼请求 (如: 1. 判令被告偿还借款本金人民币100,000元 2. 判令被告支付利息...)",
      factsAndReasons: "事实与理由 (如: 原告与被告系朋友关系。2022年5月10日，被告以生意资金周转为由向原告借款...)",
    });

    const placeholderModal = reactive({ visible: false, title: "", content: "" });
    const openPlaceholderModal = (fieldKey, title) => {
      placeholderModal.title = title;
      placeholderModal.content = placeholders[fieldKey] || "";
      placeholderModal.visible = true;
    };
    const closePlaceholderModal = () => {
      placeholderModal.visible = false;
    };

    const selectCase = (caseType) => {
      console.log("选择案由:", caseType);
      currentStep.value = "input";
    };

    const downloadFile = () => {
      console.log("下载文件");
      // 这里添加下载逻辑
    };

    const shareFile = () => {
      console.log("分享文件");
      // 这里添加分享逻辑
    };

    return {
      currentStep,
      searchKeyword,
      formData,

      primaryCategories,
      selectedPrimary,
      caseMap,
      secondaryCases,
      filteredSecondaryCases,
      categoryList,
      expandedCategories,
      filteredSearchCases,

      legalRequests,
      factsAndReasons,
      placeholders,
      placeholderModal,
      openPlaceholderModal,
      closePlaceholderModal,

      selectCase,
      downloadFile,
      shareFile,
    };
  },
};
</script>
